//
//  MyAdViewController.swift
//  Automobile
//
//  Created by erkebulan elzhan on 8/22/20.
//  Copyright © 2020 erkebulan elzhan. All rights reserved.
//

import UIKit

final class MyAdViewController: UIViewController, Alertable {
    
    // MARK: - Outlets

    lazy private var adHeaderView:AdHeaderView = {
        let adHV = AdHeaderView(customIcon: UIImage(named: "dismiss"))
        adHV.delegate = self
        return adHV
    }()
    
    lazy private var spinner = SpinnerView()

    private lazy var tableView: UITableView = {
        let table = UITableView()
        table.register(CarHeaderCell.self, forCellReuseIdentifier: "CarHeaderCell")
        table.register(MyAdInfoCell.self, forCellReuseIdentifier: "MyAdInfoCell")
        table.register(MyAdActionsCell.self, forCellReuseIdentifier: "MyAdActionsCell")
        table.register(MyAdSwitchCell.self, forCellReuseIdentifier: "MyAdSwitchCell")
        table.register(MyAdComboCell.self, forCellReuseIdentifier: "MyAdComboCell")

        table.delegate = self
        table.dataSource = self
        table.separatorInset = UIEdgeInsets(top: 0, left: 16, bottom: 0, right: 16)
        table.showsVerticalScrollIndicator = false
        return table
    }()
    
    
    // MARK: - Props
    
    public var post: Post!
    
    public var comeFromCellWithIndex: Int?
    
    private var viewModel = MyAdViewModel()
    
    private var isLoading: Bool = false {
        didSet {
            isLoading ? spinner.startAnimating() : spinner.stopAnimating()
        }
    }
    
    // MARK: - UI Actions

    @objc private func editAdvert () {
        let editVC = EditViewController()
        editVC.post = self.post
        self.navigationController?.pushViewController(editVC, animated: true)
    }

    @objc private func updateStatus () {
        if (post.status == .archived) {
            self.setStatus(status: .active)
        } else {
            self.setStatus(status: .archived)
        }
    }
    
    // MARK: - Life-Cycle
    
    override func viewDidLoad() {
        super.viewDidLoad()
        self.viewModel.setUpCells(advert: self.post)
        self.setUpUI()
    }
    
    override func viewWillAppear(_ animated: Bool) {
        self.setUpNavBar()
    }
}

// MARK: - Methods


extension MyAdViewController: AdHeaderViewDelegate {
    
    func headerButtonPressed() {
        let userInfo = ["post": self.post as Any, "index": comeFromCellWithIndex as Any] as [String : Any]
        
        NotificationCenter.default.post(name: NSNotification.Name(rawValue: "adHomeUpdate"), object: nil, userInfo: userInfo)
        self.navigationController?.popViewController(animated: true)
    }
   
    private func setStatus (status: ADStatus) {
        var request = URLRequest(url: Request(base: .advert).getUrl(path: "adverts/my/\(post.id)/"))
        request.httpMethod = "PATCH"
        self.isLoading = true
        
        Backend().fetchFromBackend(for: Bool.self, request: request, statusCode: 200, sendBool: true, sendBody: true, body: ["status": status.rawValue]) { (result) in
            
            self.isLoading = false
            switch result {
            case .failure(let err):
                self.alertError(error: err)
            case .success(_):
                self.navigationController?.dismiss(animated: true, completion: nil)
                self.post.status = status
                self.viewModel.setUpCells(advert: self.post)
                self.tableView.reloadData()
            }
        }
    }
}


// MARK: - UITable View

extension MyAdViewController: UITableViewDelegate, UITableViewDataSource {
    
    func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        return viewModel.items.count
    }
    
    func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
        let item = viewModel.items[indexPath.row]
        let cell = tableView.dequeueReusableCell(withIdentifier: type(of: item).reuseId)!
        
        if cell is CarHeaderCell {
            (cell as! CarHeaderCell).updateFullScreen()
        } else if cell is MyAdActionsCell {
            (cell as! MyAdActionsCell).editBtn.addTarget(self, action: #selector(editAdvert), for: .touchUpInside)
            (cell as! MyAdActionsCell).stopBtn.addTarget(self, action: #selector(updateStatus), for: .touchUpInside)
        }
        
        item.configure(cell: cell, index: indexPath.row)
        cell.selectionStyle = .none
        return cell
    }
}



// MARK: - UI

extension MyAdViewController {
    
    private func setUpUI () {
        view.backgroundColor = .white
        self.view.addSubview(tableView)
        self.view.addSubview(spinner)
        self.view.addSubview(adHeaderView)
        self.addConstraints()
    }
    
    private func addConstraints () {
        adHeaderView.snp.makeConstraints { (make) in
            make.top.equalTo(view.safeAreaLayoutGuide).offset(16)
            make.height.equalTo(76)
            make.leading.trailing.equalToSuperview()
        }
        tableView.snp.makeConstraints { (make) in
            make.top.equalTo(adHeaderView.snp.bottom)
            make.bottom.equalTo(view.safeAreaLayoutGuide)
            make.leading.trailing.equalToSuperview()
        }
        spinner.snp.makeConstraints { (make) in
            make.center.equalToSuperview()
        }
    }
    
    private func setUpNavBar () {
        navigationItem.largeTitleDisplayMode = .never
    }
    
    private func alertError (error: RequestError) {
       switch error {
           case .general:
               self.showAlert("Упс...", "Неизвестная ошибка")
           case .parameter(let message):
              self.showAlert("Упс...", message)
       }
    }
}
